var express = require('express');
var router = express.Router();
const { Chapter, Course } = require('../../models');
const { Op } = require('sequelize');

router.get('/', async function(req, res, next) {
  try {
    const { title, courseId } = req.query;
    const currentPage = parseInt(req.query.currentPage) || 1; // 当前页码，默认为 1
    const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
    const offset = (currentPage - 1) * pageSize;

    if (!courseId) {
      throw new Error('课程 ID 必须提供');
    }
    const condition = {
      attributes: { exclude: ['CourseId'] },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name'] // 只返回课程的 id 和 name
        }
      ],
      where: {
        CourseId: {
          [Op.eq]: courseId // 确保查询的章节属于指定的课程
        }
      },
      order: [['rank', 'ASC'], ['id', 'DESC']], // 按照 id 降序排列
      limit: pageSize,
      offset: offset
    }
    if (title) {
      condition.where.title = {
        [Op.like]: `%${title}%` // 模糊查询标题
      }
    }
    // 查询所有章节
    const { rows, count } = await Chapter.findAndCountAll(condition)
    res.json({
      status: true,
      message: 'chapter route',
      data: {
        chapters: rows,
        pagination: {
          pageSize,
          currentPage,
          total: count
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch chapters',
      error: [error.message]
    });
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ['CourseId'] },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name'] // 只返回课程的 id 和 name
        }
      ]
    };
    // 查询主键 id 的章节
    const chapter = await Chapter.findByPk(id, condition);
    if (!chapter) {
      return res.status(404).json({
        status: false,
        message: 'Chapter not found',
      });
    }
    res.json({
      status: true,
      message: 'Chapter fetched successfully',
      data: {
        chapter
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch chapter',
      error: [error.message]
    });
  }
})

router.post('/', async function(req, res, next) {
  try {
    const chapter = await Chapter.create(filterBody(req.body));
    await Course.increment('chaptersCount', { where: { id: chapter.CourseId } });
    res.status(201).json({
      status: true,
      message: 'Chapter created successfully',
      data: {
        chapter
      }
    });
  } catch (error) {
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        status: false,
        message: '请求参数错误',
        error: error.errors.map(err => err.message)
      });
    } else {
      res.status(500).json({
        status: false,
        message: 'Failed to create chapter',
        error: [error.message]
      });
    }
  }
})

router.delete('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const chapter = await Chapter.findByPk(id);
    if (!chapter) {
      return res.status(404).json({
        status: false,
        message: 'Chapter not found',
      });
    }
    await chapter.destroy();
    await Course.decrement('chaptersCount', { where: { id: chapter.CourseId } });
    res.json({
      status: true,
      message: 'Chapter deleted successfully',
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to delete chapter',
      error: [error.message]
    });
  }
})

router.put('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const chapter = await Chapter.findByPk(id);
    if (!chapter) {
      return res.status(404).json({
        status: false,
        message: 'Chapter not found',
      });
    }
    await chapter.update(filterBody(req.body));
    res.json({
      status: true,
      message: 'Chapter update successfully',
      data: {
        chapter
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to update chapter',
      error: [error.message]
    });
  }
})

function filterBody(body) {
  const { title, content } = body;
  return {
    title: title ? title.trim() : '',
    content: content ? content.trim() : ''
  };
}

module.exports = router;
